import requests

from com.utils import dbutil
from com.lechebang import Setting
from pyquery import PyQuery as pq

# dealer 的Id
#品牌车型分为3级：品牌-主机厂-车型


def get_brandAndCarSeries(dealerUrl):
    print(dealerUrl)
    heaerData={}
    heaerData=Setting.get_headers()
    heaerData['Referer']='https://dealer.autohome.com.cn/beijing'
    result=requests.get(dealerUrl,headers=heaerData, proxies=Setting.PROXY, verify=False)   # verify=False 增加此参数可以避免服务端证书验证
    if result.status_code == 200:
         tmp = result.text
         # print(tmp)
         #解析数据
         data = parse(tmp)
         print(data)
         return data
    else:
         return None
    print("================get data finished!!")


#解析品牌数据
def parse(html):
    htmldata = pq(html)
    brandTree=htmldata('div.brandtree')
    #len()=0表示此节点没有获取到，由于PyQuery类型数据，即使没有取到节点，仍然不是None，只能根据len进行判断
    if brandTree.__len__()==0:
        print('=====>解析数据错误！！')
        return None

    brandPic='https:'+brandTree('div.brandtree-name p.pic')('img').attr('src')
    brandName=brandTree('div.brandtree-name p.text').text()
    factoryHtml=brandTree('dl.tree-dl').items()

    brandAndCarSeries={} #品牌与车型
    brandAndCarSeries['brandName']=brandName
    brandAndCarSeries['brandPic']=brandPic
    factories=[]  #主机厂


    #获取主机厂
    for item in factoryHtml:
        factory={}
        carSeries = []  # 车型
        factoryName=item('dt a').text()
        factoryUrl=Setting.AUTOHOME_HOMEPAGE+item('dt a').attr('href')

        #获取这个主机厂下面的车型
        carSeriesHtml=item('dd').items()
        for item2 in carSeriesHtml:
            carSery = {}
            carSery['carSeriesName']=item2('a').text()
            carSery['carSeriesUrl']=item2('a').attr('href')
            carSeries.append(carSery)

        factory['carSeries']=carSeries
        factory['factoryName'] = factoryName
        factory['factoryUrl'] = factoryUrl

        factories.append(factory)

    brandAndCarSeries['factories']=factories

    return brandAndCarSeries


def saveBrand(delerId,brand, table):
    connection = dbutil.connectDB('lcb_mars_db')
    cursor = connection.cursor()
    factories=brand['factories']
    for factory in factories:
        carSeries=factory['carSeries']
        for carSery in carSeries:
            insertsql = "insert into %s " \
                    "(delear_id,name,pic,factory_name,factory_url,carSeries_name,carSeries_url)"\
                    "values (%d,'%s','%s','%s','%s','%s','%s')" \
                    % (table,delerId,brand['brandName'], brand['brandPic'], factory['factoryName'], factory['factoryUrl'], carSery['carSeriesName'],carSery['carSeriesUrl'])
            print(insertsql)
            cursor.execute(insertsql)
    # cursor.executemany(sql,data)
    connection.commit()
    cursor.close()
    dbutil.closeDB(connection)


if __name__ == '__main__':
    brand=get_brandAndCarSeries('https://dealer.autohome.com.cn/70063')
    print(brand)

